package com.example.geoserverdemo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.postgis.LineString;
import org.postgis.MultiLineString;
import org.postgis.PGgeometry;
import org.postgis.Point;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(CMLine.class)
public class MLineHandler extends BaseTypeHandler<CMLine> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, CMLine cPolygon, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public CMLine getNullableResult(ResultSet resultSet, String s) throws SQLException {
        List<List<double[]>> coordinates = new ArrayList<>();

        PGgeometry pGgeometry = (PGgeometry) resultSet.getObject(s);
        MultiLineString multiLineString = (MultiLineString) pGgeometry.getGeometry();
        if(multiLineString.getLines().length == 0) return null;

        // 解析点
        for(LineString lineString : multiLineString.getLines()){
            List<double[]> lineCoord = new ArrayList<>();
            for (Point point : lineString.getPoints()){
                double[] coord = new double[]{point.x, point.y};
                lineCoord.add(coord);
            }
            coordinates.add(lineCoord);
        }

        CMLine mLine = new CMLine();
        mLine.setCoordinates(coordinates);
        return mLine;
    }

    @Override
    public CMLine getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public CMLine getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
